package com.xunshibao.tutor.user.service;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xunshibao.core.BaseDRO;
import com.xunshibao.tutor.po.User;
import com.xunshibao.tutor.user.dao.UserDaoImpl;

@Service
public class UserLoginServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(UserLoginServiceImpl.class); 
    @Autowired
    private UserDaoImpl userDao;
    
    public BaseDRO login(String username, String password, String ip) {
    	BaseDRO dro = new BaseDRO();
        User user = userDao.login(username);
        if(user != null) {
            if(password.equals(user.getPwd())) {
                Date loginDate = new Date();
                //TODO 添加登录次数
                int result = userDao.updateLogin(user.getId(), ip, loginDate);
                if(result != 1) {
                    //TODO 记录登录更新失败
                    logger.error("登录成功，但登录更新失败");
                }
                dro.setStatus(0); //登录成功
                dro.setResult(user);
            } else {
            	dro.setStatus(-2);// 密码错误
            }
        } else {
        	dro.setStatus(-1) ;// 用户名不存在
        }
        return dro;
    }
    
    public int register(String uname, String password, String ip) {
        String username = userDao.validUsername(uname);
        if(username != null) {
            return -1;//用户名已经存在
        } else {
            Date regDate = new Date();
            //TODO 用户密码加密
            
            int result = userDao.regUser(uname, password, ip, regDate);
            if(result == 1) {
                return 0;
            } else {
                return -2;// 注册失败
            }
        }
    }
    
    /**
     * 检查该用户名是否被注册
     * @param username
     * @return
     * true被注册过
     * false没有被注册过
     */
    public boolean isUserExists(String uname) {
        String username = userDao.validUsername(uname);
        if(username != null) {
            return true;
        } else {
            return false;
        }
    }
    
    public int retrivePassword(Long userId) {
        return 0;
    }
}
